<?php

namespace App\Models\Backend\System;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Services\Backend\System\GroupService;
use Hamcrest\Type\IsObject;

class User extends Authenticatable
{
    protected $table = 'users';
    protected $guarded = [];
    protected $appends = ['school_id'];

    const ACTIVE_FLAG_FORBIDDEN = 0;
    const ACTIVE_FLAG_ACTIVE    = 1;
    const ACTIVE_FLAG_PENDING   = 2;

    private static $active_flags = [
        self::ACTIVE_FLAG_FORBIDDEN => '禁用',
        self::ACTIVE_FLAG_ACTIVE    => '正常',
        self::ACTIVE_FLAG_PENDING   => '未通过验证',
    ];

    const ADMIN_FLAG_SHARE  = -1;
    const ADMIN_FLAG_NONE   = 0;
    const ADMIN_FLAG_GROUP  = 1;
    const ADMIN_FLAG_SUPER  = 2;

    private static $admin_flags = [
        self::ADMIN_FLAG_SHARE => '公共帐号',
        self::ADMIN_FLAG_NONE  => '普通用户',
        self::ADMIN_FLAG_GROUP => '组管理员',
        self::ADMIN_FLAG_SUPER => '系统管理员',
    ];

    /**
     * 用户拥有的角色
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function getSchoolIdAttribute()
    {
        $key = 'group_id';

        if (array_key_exists($key, $this->attributes)){
            $groupId = $this->attributes[$key];

            $school = $this->getSchoolByGroupId($groupId);

            return $school->id;
        }

        return;
    }

    /**
     * 获取与用户关联的学校
     */
    public function school()
    {
        $school = null;
        $group_id = $this->group_id;
        if(!$group_id){
            return (object)['id'=>'','group_name'=>''];
        }
        /** @var GroupService $groupService */
        $groupService = app('groupService');
        $group_flag = 0;
        while ($group_flag != 1) {
            $filters = [['id', '=', $group_id]];
            $group = $groupService->getCore($filters, FALSE);

            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];
            if ($group_flag == 1 || $parent_id == 0) {
                $school = $group;
                break;
            } else {
                $group_id = $group['parent_id'];
            }
        }

        return $school;
    }

    /**
     * 通过group_id获取学校xinx
     * @author lxy
     * @datetime 2021-11-22
     */
    public function getSchoolByGroupId($group_id)
    {
        if(!$group_id){
            return (object)[
                'group_name' => '',
                'id' => ''
            ];
        }
        $school = (object)[
            'group_name' => '',
            'id' => ''
        ];
        /** @var GroupService $groupService */
        $groupService = app('groupService');
        $group_flag = 0;
        while ($group_flag != 1) {
            $filters = [['id', '=', $group_id]];
            $group = $groupService->getCore($filters, FALSE);
            if (!$group){
               return (object)[
                    'group_name' => '',
                    'id' => ''
                ];
            }
            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];
            if ($group_flag == 1 || $parent_id == 0) {
                return $school = $group;
                break;
            } else {
                $group_id = $group['parent_id'];
            }
        }

        return $school;
    }

    public static function getSchoolId($group_id)
    {
        if(!$group_id){
            return (object)[
                'group_name' => '',
                'id' => ''
            ];
        }
        $school = (object)[
            'group_name' => '',
            'id' => ''
        ];
        /** @var GroupService $groupService */
        $groupService = app('groupService');
        $group_flag = 0;
        while ($group_flag != 1) {
            $filters = [['id', '=', $group_id]];
            $group = $groupService->getCore($filters, FALSE);
            if (!$group){
                return (object)[
                    'group_name' => '',
                    'id' => ''
                ];
            }
            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];
            if ($group_flag == 1 || $parent_id == 0) {
                return $school = $group;
                break;
            } else {
                $group_id = $group['parent_id'];
            }
        }

        return $school;
    }

    /**
     * 以当前id为线索id,获取下面所有的id（包含线索id）
     * @author lxy
     * @datetime 2021-09-26
     * @param $sid  array  线索id [5482]
     * @param $rid  array  下级id
     * @return array
     */
    public function getAllGroupId(array $sid , array $rid = [])
    {
        $rid = array_merge($rid,$sid);
        $group = Group::whereIn('parent_id',$sid)->select('id')->get()->toArray();
        if(!$group){
            return $rid;
        }
        $pid = array_column($group,'id');
        return $this->getAllGroupId($pid,$rid);
    }

    /**
     * 获取与用户关联的学校组id
     */
    public function schoolid()
    {
        $school = $this->school();

        return $school['id'];
    }

    //获取用户权限操作
    public function getUserOper()
    {
        $powers = [];
        $roles = $this->roles()->get();
        if ($roles) {
            foreach ($roles as $role) {
                $rolepowers = $role->powers()->get();
                $rolepowers = $rolepowers->toArray();
                $rolepowers = array_column($rolepowers, 'actionid');
                $powers = array_keys(array_flip($powers) + array_flip($rolepowers));
            }
        }

        return $powers;
    }

    //获取用户权限菜单
    public function getUserMenus()
    {
        $roles = $this->roles()->get();
        return [];
    }

    /**
     * 保存来自中心 UAC 的用户数据
     *
     * @param array $data 来自中心 UAC 的用户数据数组
     */
    public static function saveUserFromCenter($data)
    {
        $fields = ['user_id', 'group_id', 'user_name', 'nickname', 'birthday', 'gender', 'email', 'create_date', 'active_flag', 'admin_flag', 'user_type', 'id_card', 'is_del'];
        $update_data = [];
        foreach ($fields as $field) {
            if (isset($data[$field])) {
                if ($field == 'create_date' && !$data[$field]) {
                    $data[$field] = date('Y-m-d H:i:s');
                }
                if ($field == 'birthday') {
                    if (!empty($data[$field])) {
                        $update_data[$field] = $data[$field];
                    }
                }
                if ($field == 'create_date') {
                    if ($data[$field] !== '0000-00-00 00:00:00') {
                        $update_data[$field] = $data[$field];
                    }
                } else {
                    $update_data[$field] = $data[$field];
                }
            }
        }

        $user = self::updateOrCreate(
            ['user_uuid' => $data['user_uuid']],
            $update_data
        );

        // 节点版最上层组的组管理员在节点版是学校管理员（类似中心版的超级管理员）
        if (isset($update_data['group_id']) && isset($update_data['admin_flag']) && ($update_data['admin_flag'] == self::ADMIN_FLAG_SUPER || $update_data['admin_flag'] == self::ADMIN_FLAG_GROUP)) {
            $user->roles()->detach();
            $user->roles()->attach(SYSTEMADMIN_ROLEID);
            //            $group = Group::find($update_data['group_id']);
            //            if ($group && $group->parent_id == 0) {
            //                $update_data['admin_flag'] = self::ADMIN_FLAG_SUPER;
            //            }
        }
    }

    /**
     * 保存来自中心 UAC 的用户数据(rpc)
     *
     * @param array $data 来自中心 UAC 的用户数据数组
     */
    public static function saveUserFromCenter_rpc($data)
    {
        $fields = ['user_id','group_id', 'user_name', 'nickname', 'birthday', 'gender', 'email', 'create_date', 'active_flag', 'admin_flag', 'user_type', 'id_card', 'is_del'];
        $update_data = [];
        foreach ($fields as $field) {
            if (isset($data[$field])) {
                if ($field == 'create_date' && !$data[$field]) {
                    $data[$field] = date('Y-m-d H:i:s');
                }
                if ($field == 'birthday') {
                    if (!empty($data[$field])) {
                        $update_data[$field] = $data[$field];
                    }
                } else {
                    $update_data[$field] = $data[$field];
                }
            }
        }
        //$data['user_id'] = isset($data['user_id']) ? $data['user_id'] : '';
        $user = self::updateOrCreate(
            ['user_id' => $data['user_id']],
            $update_data
        );

        $roles = $user->roles()->get();
        $roles = $roles->toArray();
        if(empty($roles)){
            $roleids = [];
        }else{
            $roleids = array_column($roles, 'id');
        }

        // 节点版最上层组的组管理员在节点版是学校管理员（类似中心版的超级管理员）
        if (isset($update_data['group_id']) && isset($update_data['admin_flag']) && $update_data['admin_flag'] == self::ADMIN_FLAG_SUPER) {
            if(!in_array(SYSTEMADMIN_ROLEID,$roleids)){
                $user->roles()->attach(SYSTEMADMIN_ROLEID);
            }
            //            $group = Group::find($update_data['group_id']);
            //            if ($group && $group->parent_id == 0) {
            //                $update_data['admin_flag'] = self::ADMIN_FLAG_SUPER;
            //            }
        }else {
            $role = $user->roles()->get()->first();
            if (!$role) {
                //                $user->roles()->detach();

                if (isset($update_data['user_type']) && ($update_data['user_type'][2] == '1')) {
                    $user->roles()->attach(TEACHER_ROLEID);
                }
            }
        }
    }

    public function getTeacher()
    {
        return DB::table('teachers')->where('teacher_id', '=', $this->user_uuid)->first();
    }
}
